import { useSelector, useDispatch } from 'react-redux'
import { useRef } from 'react'
import './TodoList.css'
import { addListStore, deleteListStore, toggleAllStore, toggleItem } from '../../store/modules/todoListStore'
function TodoList() {
  const dispatch = useDispatch() //触发器
  const { list } = useSelector((state) => state.todoList)
  const inputRef = useRef(null);
  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault(); 
      addList(); 
    }
  };
  const addList = () => {  //添加标签
    const value = inputRef.current.value.trim()
    if (value) {
      const newTodo = {  // 创建完整的todo对象
        id: Date.now(),  // 生成唯一ID
        title: value,    // 使用输入值作为title
        completed: false // 默认未完成
      }
      dispatch(addListStore(newTodo)) // 传递完整对象
      inputRef.current.value = ''
    }
  }
  const deleteList = (id) => {  //删除目标标签
    dispatch(deleteListStore(id))
  }
  const handleToggleAll = () => {
    //如果已经全选则取消，否则全选
    const shouldComplete = !list.every(item => item.completed);
    dispatch(toggleAllStore(shouldComplete));
  };
  const _toggleItem = (id) => {
  dispatch(toggleItem(id));
};

  return (
    <section className="todoapp">
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          autoFocus
          autoComplete="off"
          placeholder="What needs to be done?"
          ref={inputRef}
          onKeyDown={handleKeyDown}
        />
      </header>
      <section className="main">
        <input id="toggle-all" className="toggle-all" type="checkbox" onChange={handleToggleAll}
          checked={list.length > 0 && list.every(item => item.completed)} />
        <label htmlFor="toggle-all"></label>
        <ul className="todo-list">
          {list.map(item => (
            <li key={item.id} className="todo">
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.completed}
                  onChange={() => _toggleItem(item.id)}
                />
                <label>{item.title}</label>
                <button
                  className="destroy"
                  onClick={() => deleteList(item.id)}
                ></button>
              </div>
            </li>
          ))}
        </ul>
      </section>
    </section>
  )
}
export default TodoList